package com.example.application4.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

    // 数据库名称
    private static final String DATABASE_NAME = "UserDatabase.db";
    // 数据库版本号
    private static final int DATABASE_VERSION = 1;

    // 用户表的表名
    public static final String TABLE_USERS = "users";
    // 用户表的列名
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_EMAIL = "email";

    // 创建用户表的 SQL 语句
    private static final String CREATE_TABLE_USERS = "CREATE TABLE " + TABLE_USERS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_USERNAME + " TEXT NOT NULL, "
            + COLUMN_PASSWORD + " TEXT NOT NULL, "
            + COLUMN_EMAIL + " TEXT NOT NULL);";

    public DatabaseHelper(Context context) {
        // 调用父类构造函数，初始化数据库帮助器
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 当数据库第一次被创建时调用此方法
        try {
            // 执行创建用户表的 SQL 语句
            db.execSQL(CREATE_TABLE_USERS);
        } catch (Exception e) {
            // 记录创建表时的错误
            Log.e("DatabaseHelper", "Error while creating table: " + e.getMessage());
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 当数据库版本号增加时调用此方法
        try {
            // 删除旧的用户表
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
            // 重新创建用户表
            onCreate(db);
        } catch (Exception e) {
            // 记录升级数据库时的错误
            Log.e("DatabaseHelper", "Error during upgrading database: " + e.getMessage());
        }
    }
}